﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using JRCore.protocol;

namespace YoSunSDK
{
    /// <summary>
    /// 按照友上结构体的数据类型协议，进行转换
    /// </summary>
    public class YoSunAdapter
    {
        /// <summary>
        /// 构造以默认转换为友上协议
        /// </summary>
        /// <param name="DRRecord"></param>
        public YoSunAdapter(DataRecvRecord DRRecord)
        { 
        }

        public static YoSunStruct trans(DataRecvRecord DRRecord)
        {
            //友上协议的消息
            YoSunStruct YSStruct = new YoSunStruct();
            
            if (DRRecord != null)
            {
                //head.len = (ushort)(Marshal.SizeOf(msg));
                YSStruct.YSHead.len = (ushort)598;
                YSStruct.YSHead.type = 1;
                YSStruct.YSHead.ver = 4;

                #region 友上消息体赋值
                //图片数据长度
                YSStruct.YSRecord.fileSize = 0;

                //方向：01-由东向西,02-由东向南,03-由东向北,04-由南向北,05-由南向西,06-由南向东,;07-由西向东,08-由西向北,09-由西向南,10-由北向南,11-由北向东,12-由北向西,13-进城,14-出城
                switch (DRRecord.P16)
                {
                    case "1":
                        YSStruct.YSRecord.direction = 01;
                        break;
                    case "2":
                        YSStruct.YSRecord.direction = 04;
                        break;
                    case "3":
                        YSStruct.YSRecord.direction = 07;
                        break;
                    case "4":
                        YSStruct.YSRecord.direction = 10;
                        break;
                    default:
                        YSStruct.YSRecord.direction = 01;
                        break;
                }

                //车道
                try
                {
                    YSStruct.YSRecord.lane = uint.Parse(DRRecord.P17);
                }
                catch { YSStruct.YSRecord.lane = 1u; }

                //过车时间
                //友上日期UTC，需要将当前过车时间转化为UTC,减去8小时
                string FormatDateTime = DRRecord.P18.Substring(0, 4) + "-" +DRRecord.P18.Substring(4, 2) + "-" +DRRecord.P18.Substring(6, 2) + " " +DRRecord.P18.Substring(8, 2) + ":" +DRRecord.P18.Substring(10, 2) + ":" +DRRecord.P18.Substring(12, 2);

                DateTime t1 = DateTime.Parse(FormatDateTime);
                DateTime t2 = DateTime.Parse("1970-01-01 00:00:00");
                TimeSpan ts = t1.Subtract(t2);
                YSStruct.YSRecord.date = (uint)(ts.TotalSeconds - 28800);
                
                //整个红灯时间，精确到秒,闯红灯时间:单位0.1秒 卡口>25, 电警<25
                YSStruct.YSRecord.redLight = (ushort)((DRRecord.P5 == "0") ? 30u : 15u);

                //设备类型:31:高清电子警察 32:高清卡口型电子警察33:高清卡口34:高清固定超速35:高清移动超速 36:高清单行线逆行
                YSStruct.YSRecord.device = (ushort)32;

                //限速值
                YSStruct.YSRecord.threshold = ushort.Parse(DRRecord.P26);

                //速度，15-999
                YSStruct.YSRecord.speed = ushort.Parse(DRRecord.P27);

                //限速比: 在限速值上放宽范围比例
                YSStruct.YSRecord.osratio = 10;

                //路口代码
                YSStruct.YSRecord.pasCode = ushort.Parse(DRRecord.P14);

                //车牌 如果是无车牌的图片，则友上平台的闯红灯中不显示该条记录
                if (DRRecord.P23 != "" && !DRRecord.P23.Contains("无"))
                {

                    //车牌首字母代码
                    string strPlateProvince = "京津晋冀蒙辽吉黑沪苏浙皖闽鲁豫鄂湘粤桂琼川贵云藏陕甘青宁渝军海空集北沈南兰广成济消水边电林通金警学特使领试港澳赣新";
                    string provinceCode = "00";

                    //取车牌中的第一个字符
                    string strPlate = DRRecord.P23[0].ToString();
                    int intPlate = (int)DRRecord.P23[0];

                    //如果第一个字符为中文
                    if (intPlate > 19968 && intPlate < 40869)
                    {
                        try
                        {
                            provinceCode = (strPlateProvince.IndexOf(strPlate) + 1).ToString().PadLeft(2, '0');
                        }
                        catch (Exception)
                        {
                            ;
                        }
                    }

                    YSStruct.YSRecord.plate1 = ushort.Parse(provinceCode);

                    //车牌后6个字符
                    YSStruct.YSRecord.plate2 = new char[6];

                    char[] source;

                    DRRecord.P23.Substring(1, 6);

                    if (DRRecord.P23.Contains("学"))
                    {
                        source = DRRecord.P23.Replace("学", "x").ToCharArray();
                    }
                    else if (DRRecord.P23.Contains("警"))
                    {
                        source = DRRecord.P23.Replace("警", "j").ToCharArray();
                    }
                    else if (DRRecord.P23.Contains("挂"))
                    {
                        source = DRRecord.P23.Replace("挂", "g").ToCharArray();
                    }
                    else
                    {
                        //因为这是友上协议的规定，plate只能放入6个字节
                        //所以，如果车牌的末尾出现中文字符，文件名已经进行了替换
                        //而给他们传送时，不发送末尾的这1位
                        source = DRRecord.P23.Substring(1, 6).ToCharArray();
                    }

                    if ((source != null) && (source.Length <= 6))
                    {
                        Array.Copy(source, YSStruct.YSRecord.plate2, source.Length);
                    }
                }
                else
                {
                    YSStruct.YSRecord.plate1 = 0;
                    YSStruct.YSRecord.plate2 = "000000".ToCharArray();
                }

                //车辆长度
                YSStruct.YSRecord.carLen = 0;

                switch (DRRecord.P22)
                {
                    case "蓝":
                        YSStruct.YSRecord.color = 1u;
                        break;
                    case "黄":
                        YSStruct.YSRecord.color = 3u;
                        break;
                    case "白":
                        YSStruct.YSRecord.color = 4u;
                        break;
                    case "黑":
                        YSStruct.YSRecord.color = 2u;
                        break;
                    default:
                        YSStruct.YSRecord.color = 1u;
                        break;
                }

                // 超速比：1 0-20%，2 20%-50%, 3 50%-70%, 4 70%以上
                YSStruct.YSRecord.overspeed = 0;

                //是否导出
                YSStruct.YSRecord.writeout = 0;

                //是否已处罚：0未处罚，1已处罚
                YSStruct.YSRecord.punish = 0;

                //抓拍位置: 1-车头，2-侧面, 3-车尾,4-顶部
                YSStruct.YSRecord.capPos = 3u;

                //比对控制/识别状态  1比对 0不比对
                YSStruct.YSRecord.recStatus = 1;

                //preassign，违章原因
                YSStruct.YSRecord.preassign = 0;

                //违法原因，具体定义见后面
                YSStruct.YSRecord.reason = 0;

                // productType
                YSStruct.YSRecord.productType = 0;

                // 转向代码: 1 左拐，2 直行，3 右拐，4 直左，5 直右
                try
                {
                    YSStruct.YSRecord.turnCode = byte.Parse(DRRecord.P17);
                }
                catch { YSStruct.YSRecord.turnCode = 2; }

                // 图片顺序 从1开始
                YSStruct.YSRecord.picOrder = 1;

                // 图片总数，如果是电警，则为3
                YSStruct.YSRecord.picCount = 1;

                // 闯红灯时间，精确到0.1秒
                YSStruct.YSRecord.redLightTime = 30;

                // ta1
                YSStruct.YSRecord.ta1 = 0;

                // ta2
                YSStruct.YSRecord.ta2 = 0;

                //友上的结构体中，规定卡口为1
                //友上的文件名中，规定卡口为0，所以，到了文件名生成那里，再转一下
                YSStruct.YSRecord.picType = (byte)((DRRecord.P5 == "0") ? 1 : 0);

                //0 正常, 1 逆行
                YSStruct.YSRecord.state = 0;

                //图片存储设备的 ip地址
                //友上的系统中记录每个路口所对应的存储设备名
                //这里的IP地址是非必需的
                //todo 存储设备的IP
                YSStruct.YSRecord.ip = new char[16];
                char[] storeip = "172.25.70.87".ToCharArray();

                if ((storeip != null) && (storeip.Length <= 16))
                {
                    Array.Copy(storeip, YSStruct.YSRecord.ip, storeip.Length);
                }

                //以字节数组的方式存储路径名
                //172.25.70.86/data/20150430/60/pic/32_60_04_1_20150430225447_30_000_110_10_0000_10AY83D1_1_3_1_00_0000_0_0_1_1_1_0000_1000_0000_0000_2000.jpg
                string subPath = string.Empty;
                if (DRRecord.P37 != null && DRRecord.P37.Contains("data") && DRRecord.P37.Contains("pic"))
                {
                    int firstPos = DRRecord.P37.IndexOf("data") - 1;
                    int secPos = DRRecord.P37.IndexOf("pic") - 1;
                    //截取路径/data/20150430/60
                    subPath = DRRecord.P37.Substring(firstPos, secPos - firstPos);
                }
                else
                {
                    subPath = "/data"+"/" + DRRecord.P18.Substring(0, 6) +"/" +DRRecord.P14;
                }

                byte[] bytePic = System.Text.Encoding.UTF8.GetBytes(subPath);
                YSStruct.YSRecord.path = new byte[256];
                for (int i = 0; i < bytePic.Length; i++)
                {
                    YSStruct.YSRecord.path[i] = bytePic[i];
                }
                    
                // 车牌图片文件大小：0 代表无车牌
                YSStruct.YSRecord.plateSize = (uint)((DRRecord.Pic5 == null) ? 0 : DRRecord.Pic5.Length);

                // 红名单告警： 0 不是，1是
                YSStruct.YSRecord.vip = 0;

                // 模糊车牌告警： 0不是，1是
                YSStruct.YSRecord.fuzzy = 0;

                // 布控信息，utf8编码
                YSStruct.YSRecord.bkInfo = new char[256];

                //区域代码
                YSStruct.YSRecord.areaCode = new char[8];

                //系统信息
                YSStruct.YSRecord.sysNum = new char[8];

                //过车时间
                YSStruct.YSRecord.ms = 0;

                //车身颜色
                YSStruct.YSRecord.vbColor = ushort.Parse(DRRecord.P24);
                #endregion

                YSStruct.YSPlate.byteYosunPlate = DRRecord.Pic5;    
    
                return YSStruct;
            }
            return YSStruct;
            
        }

    }
}
